import random
from flask import Flask, render_template, session, g, request
from flask_sqlalchemy import SQLAlchemy

# 导入自定义过滤器
from filters import FILTERS

# 导入flask_wrf的防范机制类
from flask_wtf import CSRFProtect


app = Flask(__name__, template_folder='templates')

# 配置
app.config.update({
    "DEBUG" : True,
    "SECRET_KEY" : "dalkfjadflkuoiwerkqwrxxxd!(#!(*&#(*ldjkfalkjdfalk)))dafadfaf",
})

# 把csrf注册到app里面去
csrf = CSRFProtect()
csrf.init_app(app)

# 批量注册自定义过滤器
for key, value in FILTERS.items():
    app.add_template_filter(value, key)

# 连接数据库
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://zhangyz:123456@10.4.7.13:3306/school?charset=utf8mb4"
# 动态追踪修改设置, 如未设置只会提示警告
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
# 查询时会显示原始SQL语句
app.config["SQLALCHEMY_ECHO"] = True

# 把SQLAlchemy组件注册到项目中
db = SQLAlchemy()
db.init_app(app)


@app.route("/")
def index():
    html = render_template("index2.html", **locals())
    return html

@app.route("/index3")
def index3():
    # 比较复杂的数据结构
    book_list = [
        {"id": 109, "title": "图书标题109", "description": "图书介绍"},
        {"id": 180, "title": "图书标题180", "description": "图书介绍"},
        {"id": 181, "title": "图书标题181", "description": "图书介绍"},
    ]

    html = render_template("index3.html", **locals())
    return html

@app.route("/user")
def user():
    title = "用户中心"
    html = render_template("index_user.html", **locals())
    return html

@app.route("/transfer", methods=["post"])
def transfer():
    return "转账成功!"


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)